﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using CPlatePrintSys.Application.ViewModels;
using CPlatePrintSys.Domain.Events;
using Prism.Events;
using Prism.Ioc;

namespace CPlatePrintSys.Application.Views
{
    /// <summary>
    /// UserAddOrEditView.xaml 的交互逻辑
    /// </summary>
    public partial class UserAddOrEditView : MetroWindow
    {
        private IEventAggregator _eventAggregator;
        public UserAddOrEditView()
        {
            _eventAggregator = (IEventAggregator)Prism.Ioc.ContainerLocator.Container.Resolve<IEventAggregator>();

            InitializeComponent();
            this.Loaded += UserAddOrEditView_Loaded;
            this.Closed += UserAddOrEditView_Closed;
        }

        private void UserAddOrEditView_Closed(object sender, EventArgs e)
        {
            _eventAggregator.GetEvent<WindowsPopupedEvent>().Publish(false);
        }

        private void UserAddOrEditView_Loaded(object sender, RoutedEventArgs e)
        {
            _eventAggregator.GetEvent<WindowsPopupedEvent>().Publish(true);

            if (DataContext is UserAddOrEditViewModel viewModel)
            {
                // Correctly handle PasswordBox binding since PasswordBox.Password is not a dependency property
                PasswordBox.PasswordChanged += (s, args) =>
                {
                    if (s is PasswordBox passwordBox)
                    {
                        viewModel.User.Password = passwordBox.Password;
                    }
                };

                //ConfirmPasswordBox.PasswordChanged += (s, args) =>
                //{
                //    if (s is PasswordBox confirmPasswordBox)
                //    {
                //        viewModel.ConfirmPassword = confirmPasswordBox.Password;
                //    }
                //};

                // Subscribe to RequestClose event
                viewModel.RequestClose += (result) =>
                {
                    this.DialogResult = result.Result == Prism.Dialogs.ButtonResult.OK;
                    this.Close();
                };
            }
        }

        private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (DataContext is CPlatePrintSys.Application.ViewModels.UserAddOrEditViewModel vm)
            {
                // Directly assign the value to the Password property instead of using SetProperty
                vm.User.Password = PasswordBox.Password;

                // Raise the property changed event manually for the Password property
                vm.InvokeRaiseUpdate(vm.User.Password);

                // Update the SaveCommand's CanExecute state
                (vm.SaveCommand as Prism.Commands.DelegateCommand)?.RaiseCanExecuteChanged();
            }
        }

        private void ConfirmPasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (DataContext is CPlatePrintSys.Application.ViewModels.UserAddOrEditViewModel vm)
            {
                // Directly assign the value to the ConfirmPassword property instead of using SetProperty
                //vm.ConfirmPassword = ConfirmPasswordBox.Password;

                // Raise the property changed event manually for the ConfirmPassword property
                vm.InvokeRaiseUpdate(vm.User.Password);

                // Update the SaveCommand's CanExecute state
                (vm.SaveCommand as Prism.Commands.DelegateCommand)?.RaiseCanExecuteChanged();
            }
        }

        private void UsernameTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // 只允许英文字符输入（a-z, A-Z）
            foreach (char c in e.Text)
            {
                if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')))
                {
                    e.Handled = true;
                    return;
                }
            }
        }

        private void UsernameTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            // 阻止粘贴等操作输入非英文字符
            if (e.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                // 检查剪贴板内容
                if (Clipboard.ContainsText())
                {
                    string clipboardText = Clipboard.GetText();
                    foreach (char c in clipboardText)
                    {
                        if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')))
                        {
                            e.Handled = true;
                            return;
                        }
                    }
                }
            }
        }

        private void UsernameTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 确保文本只包含英文字符
            if (sender is TextBox textBox)
            {
                string text = textBox.Text;
                string filteredText = "";
                
                foreach (char c in text)
                {
                    if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
                    {
                        filteredText += c;
                    }
                }
                
                if (text != filteredText)
                {
                    textBox.Text = filteredText;
                    textBox.CaretIndex = filteredText.Length;
                }
            }
        }
    }
}
